package com.prince.web.service.impl;

import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.enums.FundDirectionEnum;
import com.prince.mapper.CustomerMapper;
import com.prince.mapper.CustomerOrderMapper;
import com.prince.mapper.SupplierMapper;
import com.prince.model.*;
import com.prince.page.Page;
import com.prince.util.*;
import com.prince.web.service.SupplierService;
import com.prince.web.service.UserOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 供应商
 * @Author: 王培喜 58528792@163.com
 * @Date: 2021/4/6 15:05
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private UserOrderService userOrderService;
    @Resource
    private CustomerOrderMapper customerOrderMapper;
    /**
     * 功能描述: 分页查询供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 15:25
     */
    @Override
    public Map<String, Object> findSupplierByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        SupplierExample example = new SupplierExample();
        SupplierExample.Criteria criteria = example.createCriteria().andDelEqualTo(Constants.YES);
        //封装条件
        if (MapUtil.isNotEmpty(params, "startTime")) {
            Date startTime = DateUtil.strToDate(params.get("startTime").toString(), "yyyy-MM-dd hh:mm:ss");
            Date endTime = DateUtil.strToDate(params.get("endTime").toString(), "yyyy-MM-dd hh:mm:ss");
            criteria.andCreatedBetween(startTime, endTime);
        }
        //联系人
        if(MapUtil.isNotEmpty(params,"name")){
            criteria.andNameLike("%"+params.get("name")+"%");
        }
        //手机号
        if(MapUtil.isNotEmpty(params,"phone")){
            criteria.andPhoneLike("%"+params.get("phone")+"%");
        }
        //厂家
        if(MapUtil.isNotEmpty(params,"supplierName")){
            criteria.andSupplierNameLike("%"+params.get("supplierName")+"%");
        }
        //地址
        if(MapUtil.isNotEmpty(params,"addr")){
            criteria.andAddrLike("%"+params.get("addr")+"%");
        }
        //拼音码
        if(MapUtil.isNotEmpty(params,"pinyin")){
            criteria.andPinyinLike(params.get("pinyin").toString());
        }
        //查询总数
        int total = supplierMapper.countByExample(example);
        if (null != page) {
            example.setPage(page);
        }
        example.setOrderByClause("created desc");
        List<Supplier> list = supplierMapper.selectByExample(example);
        return response.toHashMapByPage(total,list);
    }
    /**
     * 功能描述: 添加供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> addSupplier(Supplier supplier) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
//        //先判断是否存在 不存在再添加
//        if(StringUtil.isEmpty(supplier.getName())){
//            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.parameterNull).toHashMap();
//        }
//        //校验名称是否存在
//        boolean flag = checkTheName(supplier.getName());
//        if(flag){
//            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.dataDuplication).toHashMap();
//        }

        //添加
        supplier.setUpdater(supplier.getCreater());
        supplier.setCreated(new Date());
        supplier.setDel(Constants.YES);
        int i = supplierMapper.insertSelective(supplier);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.dataDuplication).toHashMap();
        }
        return response.toHashMap();
    }

    /**
     * 功能描述: 校验名称
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:34
     */
    private boolean checkTheName(String name){
        if(StringUtil.isEmpty(name)){
            return true;
        }
        SupplierExample example = new SupplierExample();
        SupplierExample.Criteria criteria = example.createCriteria().andDelEqualTo(Constants.YES);
        criteria.andNameEqualTo(name.trim());
        List<Supplier> units = supplierMapper.selectByExample(example);
        if(ListUtils.isNotEmpty(units)){
            return true;
        }
        return false;
    }
    /**
     * 功能描述: 修改供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> updateSupplier(Supplier supplier) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
//        if (StringUtil.isNotEmpty(supplier.getName()) && StringUtil.isNotEmpty(supplier.getRemark())
//                && StringUtil.stringNotEquals(supplier.getName(),supplier.getRemark())) {
//            //校验
//            boolean flag = checkTheName(supplier.getName());
//            if(flag){
//                return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.dataDuplication).toHashMap();
//            }
//        }
        supplier.setRemark(null);
        int i = supplierMapper.updateByPrimaryKeySelective(supplier);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.updateError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 删除供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> delSupplier(Supplier supplier) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        supplier.setDel(Constants.NO);
        int i = supplierMapper.updateByPrimaryKeySelective(supplier);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.delError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过id查询供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> findSupplierById(Integer id) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        Supplier supplier = supplierMapper.selectByPrimaryKey(id);
        response.put("data",supplier);
        return response.toHashMap();
    }

    /**
     * 功能描述: 查询所有供应商
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> findSupplierAll() {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        SupplierExample example = new SupplierExample();
        example.createCriteria().andDelEqualTo(Constants.YES);
        List<Supplier> list = supplierMapper.selectByExample(example);
        list.forEach(x->{
            x.setRemark(x.getSupplierName());
            x.setName(x.getSupplierName());
        });
        response.put("data",list);
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过拼音码查询供应商资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public List<Supplier> findSupplierByPinyin(String pinyin) {
        SupplierExample example = new SupplierExample();
        example.createCriteria().andDelEqualTo(Constants.YES).andPinyinEqualTo(pinyin);
        return supplierMapper.selectByExample(example);
    }

    /**
     * 功能描述: 分页查询客户资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 15:25
     */
    @Override
    public Map<String, Object> findCustomerByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        CustomerExample example = new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria().andDelEqualTo(Constants.YES);
        //封装条件
        if (MapUtil.isNotEmpty(params, "startTime")) {
            Date startTime = DateUtil.strToDate(params.get("startTime").toString(), "yyyy-MM-dd hh:mm:ss");
            Date endTime = DateUtil.strToDate(params.get("endTime").toString(), "yyyy-MM-dd hh:mm:ss");
            criteria.andCreatedBetween(startTime, endTime);
        }
        //联系人
        if(MapUtil.isNotEmpty(params,"name")){
            criteria.andNameLike("%"+params.get("name")+"%");
        }
        //手机号
        if(MapUtil.isNotEmpty(params,"phone")){
            criteria.andPhoneLike("%"+params.get("phone")+"%");
        }
        //地址
        if(MapUtil.isNotEmpty(params,"addr")){
            criteria.andAddrLike("%"+params.get("addr")+"%");
        }
        //拼音码
        if(MapUtil.isNotEmpty(params,"pinyin")){
            criteria.andPinyinLike("%"+params.get("pinyin") + "%");
        }

        //查询总数
        int total = customerMapper.countByExample(example);
        if (null != page) {
            example.setPage(page);
        }
        example.setOrderByClause("created desc");
        List<Customer> list = customerMapper.selectByExample(example);
        list.forEach(x->{
            x.setMd5key(null);
        });
        return response.toHashMapByPage(total,list);
    }
    /**
     * 功能描述: 添加客户资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> addCustomer(Customer customer) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        customer.setCreated(new Date());
        customer.setDel(Constants.YES);

        int i = customerMapper.insertSelective(customer);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.updateError).toHashMap();
        }
        String key = Constants.USER + customer.getId() + customer.getAmount();
        customer.setMd5key(MD5Util.encrypt(key));
        customerMapper.updateByPrimaryKeySelective(customer);
        return response.toHashMap();
    }
    /**
     * 功能描述: 修改客户资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> updateCustomer(Customer customer) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        int i = customerMapper.updateByPrimaryKeySelective(customer);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.updateError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 删除客户资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> delCustomer(Customer customer) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        customer = customerMapper.selectByPrimaryKey(customer.getId());
        if(customer.getAmount().intValue() != 0){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.NOT_AMOUT_ZERO).toHashMap();
        }

        customer.setDel(Constants.NO);
        int i = customerMapper.updateByPrimaryKeySelective(customer);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.delError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过id查询客户资料
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> findCustomerById(Integer id) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        Customer customer = customerMapper.selectByPrimaryKey(id);
        if(null != customer){
            customer.setMd5key(null);
        }
        response.put("data",customer);
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过拼音码查询客户资料 模糊匹配
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public List<Customer> findCustomerByPinyin(String pinyin) {
        if(StringUtil.isEmpty(pinyin)){
            return new ArrayList<>();
        }
        CustomerExample example = new CustomerExample();
        example.createCriteria().andPinyinLike("%" + pinyin + "%").andDelEqualTo(Constants.YES);
        List<Customer> list = customerMapper.selectByExample(example);
        list.forEach(x->{
            x.setRemark(x.getName()+"  "+x.getPhone()+"  "+x.getAddr()  + "   ￥"+x.getAmount() +"  " + x.getPinyin());
            x.setMd5key(null);
        });
        return list;
    }
    /**
     * 功能描述: 充值金额
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/5/28 17:22
     */
    @Override
    @Transactional
    public Map<String, Object> addCustomerAmount(Customer customer) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        BigDecimal amount = customer.getAmount();
        String creater = customer.getCreater();
        String described = customer.getDescribed();
        customer = customerMapper.selectByPrimaryKey(customer.getId());
        //添加
        try {
            customer.setDescribed(described);
            userOrderService.customerAmountChange(customer,null,amount,creater, FundDirectionEnum.ADD);
        } catch (Exception e) {
            e.printStackTrace();
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 查询
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/5/28 18:03
     */
    @Override
    public Map<String, Object> findcustomerOrderByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        CustomerOrderExample example = new CustomerOrderExample();
        CustomerOrderExample.Criteria criteria = example.createCriteria();
        //封装条件
//        if (MapUtil.isNotEmpty(params, "startTime")) {
//            Date startTime = DateUtil.strToDate(params.get("startTime").toString(), "yyyy-MM-dd hh:mm:ss");
//            Date endTime = DateUtil.strToDate(params.get("endTime").toString(), "yyyy-MM-dd hh:mm:ss");
//            criteria.andCreatedBetween(startTime, endTime);
//        }
        if(MapUtil.isNotEmpty(params,"customerId")){
            criteria.andCustomerIdEqualTo(Integer.valueOf(params.get("customerId").toString()));
        }
        //查询总数
        int total = customerOrderMapper.countByExample(example);
        if (null != page) {
            example.setPage(page);
        }
        example.setOrderByClause("created desc");
        List<CustomerOrder> list = customerOrderMapper.selectByExample(example);
        return response.toHashMapByPage(total,list);
    }

}
